using System;
using System.Globalization;

namespace MathService
{
    public class LambdaFormatter<T> : IFormatProvider, ICustomFormatter
    {
        private readonly Func<string, object, IFormatProvider, string> f_Formatter;
        public LambdaFormatter(Func<string, object, IFormatProvider, string> Formatter) { f_Formatter = Formatter; }

        public object GetFormat(Type formatType)
        {
            return formatType == typeof(ICustomFormatter) ? this : null;
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if(arg.GetType() != typeof(T))
                try { return HandleOtherFormats(format, arg); } catch(FormatException e)
                {
                    throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
                }

            return f_Formatter(format, arg, formatProvider);
        }

        private string HandleOtherFormats(string format, object arg)
        {
            if(arg is IFormattable)
                return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
            else if(arg != null)
                return arg.ToString();
            else
                return String.Empty;
        }

    }
}